package test;

import test.UtilAPi;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 客户端
 */
public class Home04ClientB {
    public static void main(String[] args) throws Exception {
        try {
            Socket socket = new Socket("127.0.0.1",9999);
            System.out.println("请输入要查找的歌名");
            Scanner scanner = new Scanner(System.in);
            String name = scanner.next();
            //将要查找的歌名发送给服务器
            BufferedReader bis = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter bos = new PrintWriter(socket.getOutputStream(), true);
            bos.println(name);
//            BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
//            bos.write(name.getBytes(),0,name.getBytes().length);
//            bos.flush();//清空缓存区
//            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
//            while (true){
//                int flog = bis.read();
//                if(flog == -1){
//                    System.out.println("查找结束....");
//                    break;
//                }
//                name = UtilAPi.streamToString(bis);//返回名字
//                byte[]array = UtilAPi.getByteArray(bis);//返回文件
//                try (OutputStream ops = new FileOutputStream("src/music/"+name)){
//                    ops.write(array);//将该文件写入新地址
//                    ops.flush();
//                }
//            }
            // 读取服务器返回的文件内容并保存到本地
            String response = bis.readLine();
            System.out.println(response);
            String fileName = scanner.nextLine();
            String filePath = "D:\\aaa\\" + fileName;  // 指定目录的路径
            FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
            byte[] buffer = new byte[4096];
            int bytesRead;
            InputStream inputStream = socket.getInputStream();
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }
            fileOutputStream.close();

        }catch (IOException e) {
            e.printStackTrace();
        }


    }

}
